# coding=utf-8
import types
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import RequestContext
from PublicTool import HttpWrite

__author__ = 'czq'
class ModelHelper(object):
    def __init__(self):
        self.url_list=None
        self.url_add=None
        self.model=None
        self.forms=None
        self.html_list=None
        self.moduleName=None
        self.typeName=None
        self.listUrlArgs=''
        self.baseUrl="simple/"
    def getUrlList(self):
        return HttpResponseRedirect(reverse(self.url_list))
    def getHtmlAddress(self,type):
        return "%s%s/%s_%s.html"%('',self.moduleName,self.typeName,type)
    def getReverseTypeUrl(self,type,args=('',)):
        return reverse(self.typeName+"_"+type,args=args)
    def getListReverse(self):
        try:
            if self.listUrlArgs:
                return HttpResponseRedirect(reverse( self.typeName+"_list",args=self.listUrlArgs))
        except:
            return HttpResponseRedirect(reverse(self.typeName+"_list"))
    def getReverse(self):
        return HttpResponseRedirect(reverse(self.url_list))
    def delete(self,request,id):
        obj=get_object_or_404(self.model,pk=int(id))
        obj.delete()
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    def saveResult(self,form):
        if form.is_valid():
            return form.save(commit=False)
        else:
            return None
    def save(self,request,form):
        if form.is_valid():
            form.save()
            return self.getListReverse()
        else:
            return render_to_response(self.getHtmlAddress("add"), {'form': form},context_instance=RequestContext(request))

    def add(self,request,id,addCallBack=None,upCallBack=None,reverseArgs=None):
        form=None
        if (id==""):
            if request.method == 'POST':
                form=self.forms(request.POST)
                if (addCallBack!=None):
                    model=self.saveResult(form)
                    # if 1==1:
                    #     model=form.save()
                    #     return HttpWrite.infoSuccess(model.permissions)
                    if type(addCallBack)==type(self.add):
                        callBack = addCallBack(model)
                        typeBack=(type(callBack))
                        if typeBack is types.StringType:
                            pass
                        else:
                            return callBack
                        return callBack
                    else:
                        return HttpWrite.infoSuccess(request,type(addCallBack))
                else:
                    return self.save(request,form)
            else:
                form=self.forms()
        else:
            model=get_object_or_404(self.model,pk=int(id))
            if (request.method=="POST"):
                form=self.forms(request.POST,instance=model)
                self.save(request,form)
                return self.getListReverse()
            else:
                form=self.forms(instance=model)
        return render_to_response(self.getHtmlAddress("add"), {'form': form},context_instance=RequestContext(request))

    def list(self,request,dict={},filterFun=None):
        if (filterFun==None):
            list=self.model.objects.all()
            dict["list"]=list
        else:
            dict=filterFun()
            if type(dict) is types.DictType:
                pass
            else:
                return HttpWrite.infoFailure(request,dict)

        return render_to_response(self.getHtmlAddress("list"), dict,context_instance=RequestContext(request))
    def listFilter(self):
        pass
    def show(self,request,id,dict={},submitFun=None,showFun=None):
        model=self.model.objects.get(id=id)

        if submitFun!=None:
            submitR = submitFun(request,model)
            if (submitR!=None):
                return submitR
        #else:
        if showFun!=None:
                showFun(request,model)
        dict["model"]=model
        return render_to_response(self.getHtmlAddress("show"), dict,context_instance=RequestContext(request))
    def showThisPage(self,request):
        return HttpResponseRedirect(request.META['HTTP_REFERER']+"?redirect=1")
    def index(self,request):
        return render_to_response(self.getHtmlAddress("index"), context_instance=RequestContext(request))